import React, { useState, useRef } from 'react';
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Divider, message, Tabs } from 'antd';
import ProForm, { ProFormCaptcha, ProFormText } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import { SimpleFooter } from '@/layouts/components/Footer';

import { login, getFakeCaptcha } from './service';

import { setCookie } from '@/utils/cookie';

import book from '@public/images/book.png';

import styles from './index.less';

const Login: React.FC = () => {
    const formRef: any = useRef();
    const [type, setType] = useState<string>('account');
    const { setInitialState } = useModel('@@initialState');
    const handleSubmit = async (values: AircasKB.LoginParams) => {
        try {
            // 登录
            // console.log(history);
            const msg = await login({ ...values });
            if (msg.success) {
                message.success('登录成功！');
                setCookie('Aircas-TOKEN', msg.data.authorization);
                setCookie('Aircas-User', JSON.stringify(msg.data));
                setInitialState((s) => ({
                    ...s,
                    currentUser: msg.data,
                }));
                /** 此方法会跳转到 redirect 参数所在的位置 */
                if (!history) return;
                const { query } = history.location;
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            } else {
                // console.log(msg);
                // message.error(msg.message);
            }
            // 如果失败去设置用户错误信息
        } catch (error) {
            // console.log(error);
            // message.error('用户名或密码错误，请重试！');
        }
    };

    return (
        <div className={styles.container}>
            <div className={styles.logo}>
                <a href={"/"}>
                    <img src={require('@public/images/logo-word.png')}>
                    </img>
                </a>

            </div>
            <div className={styles.book}>
                <img src={book}></img>
            </div>
            <div className={styles.form}>
                <div className={styles.tab}>
                    <Tabs activeKey={type} centered onChange={setType}>
                        <Tabs.TabPane key="account" tab={'账户密码登录'} />
                        <Tabs.TabPane key="mobile" tab={'手机号登录'} />
                    </Tabs>
                </div>
                <ProForm
                    formRef={formRef}
                    submitter={{
                        render: (props) => (
                            <Button
                                type="primary"
                                size="large"
                                block
                                className={styles.loginBtn}
                                htmlType="submit"
                            >
                                登录
                            </Button>
                        ),
                    }}
                    onFinish={handleSubmit}
                >
                    {type === 'account' && (
                        <>
                            <ProFormText
                                name="loginName"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined className={styles.prefixIcon} />,
                                }}
                                placeholder={'用户名'}
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入用户名!',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                name="password"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined className={styles.prefixIcon} />,
                                }}
                                placeholder={'密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入密码！',
                                    },
                                ]}
                            />
                        </>
                    )}
                    {type === 'mobile' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: <MobileOutlined className={styles.prefixIcon} />,
                                }}
                                name="mobile"
                                placeholder={'手机号'}
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入手机号！',
                                    },
                                    {
                                        pattern: /^1\d{10}$/,
                                        message: '手机号格式错误！',
                                    },
                                ]}
                            />
                            <ProFormCaptcha
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined className={styles.prefixIcon} />,
                                }}
                                captchaProps={{
                                    size: 'large',
                                }}
                                placeholder="请输入验证码"
                                captchaTextRender={(timing, count) => {
                                    if (timing) {
                                        return '获取验证码';
                                    }
                                    return '获取验证码';
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入验证码！',
                                    },
                                ]}
                                onGetCaptcha={async (phone) => {
                                    const result = await getFakeCaptcha({
                                        phone,
                                    });
                                    if (result === false) {
                                        return;
                                    }
                                    message.success('获取验证码成功！验证码为：1234');
                                }}
                            />
                        </>
                    )}
                </ProForm>
                <Divider>第三方登录</Divider>
                <div className={styles.other}>
                    <div className={styles.otherLogin}>
                        <div className={styles.item}>
                            <img width={48} src={require('@public/images/wx.png')} />
                            <p style={{ color: '#69b813' }}>微信</p>
                        </div>
                        <div className={styles.item}>
                            <img width={48} src={require('@public/images/qywx.png')} />
                            <p style={{ color: '#0082EF' }}>企业微信</p>
                        </div>
                        <div className={styles.item}>
                            <img width={48} src={require('@public/images/dmz.png')} />
                            <p style={{ color: '#687879' }}>地面站</p>
                        </div>
                    </div>
                    <div className={styles.tool}>
                        <Button size="small" type="link" className={styles.forgetBtn}>
                            忘记密码
                        </Button>
                        <Button size="small" type="link">
                            立即注册
                        </Button>
                    </div>
                </div>
            </div>
            <SimpleFooter />
        </div>
    );
};

export default Login;
